package com.example.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * springboot项目常用的配置文件
 */
@Configuration
public class CORSConf {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Autowired
            private MyInterceptor myInterceptor;

            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(myInterceptor)
                        .addPathPatterns("/**") // 拦截所有接口路径
                        .excludePathPatterns("/t-user/login","/banji/**","/Thymeleaf"
                                ,"/t-user/register","/t-user/getCode","/statistics"); // 排除某些接口的路径 放行对应的接口路径 "/banji/**"表示接口路径含有banji的都放行
            }
            //配置虚拟路径和实体路径的映射关系
            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
            // 此时在浏览器访问http://localhost:8082/avatar相当于访问d:/avatar目录
                registry.addResourceHandler("/avatar/***")
                        .addResourceLocations("file:d:/avatar/");
            }
            //配置跨域的
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")      // 设置映射
                        .allowedOrigins("*")        // 设置域
                        .allowedMethods("*")               // 设置请求的方式GET、POST等
                        .allowedHeaders("*");              // 设置头
            }

        };
    }
}